<template>
  <div ref="container"></div>
</template>

<script>
import { ref, onMounted } from "vue";
import {
  PivotSheet,
  S2Event,
  DataCell,
  RowCell,
  ColCell,
  CustomText,
  renderText,
  getEmptyPlaceholder,
} from "@antv/s2";

export default {
  setup() {
    const container = ref(null);
    let s2;

    onMounted(() => {
      // 工具函数：文本分行逻辑
      const splitTextIntoLines = (text, maxWidth, charWidth) => {
        const lines = [];
        let currentLine = "";

        [...text].forEach((char) => {
          const tempLine = currentLine + char;
          if (tempLine.length * charWidth > maxWidth) {
            lines.push(currentLine);
            currentLine = char;
          } else {
            currentLine = tempLine;
          }
        });
        if (currentLine) lines.push(currentLine);
        return lines;
      };

      // 工具函数：计算动态行高
      const calculateColCellHeight = (viewMeta) => {
        console.log(viewMeta, "viewMeta");
        const fontSize = 12,
          padding = 8,
          lineHeight = 14;
        const lines = splitTextIntoLines(
          viewMeta.value || "",
          viewMeta.width - 2 * padding,
          fontSize
        );
        return lines.length * lineHeight + padding * 2;
      };

      class CustomColCell extends ColCell {
        drawTextShape() {
          let { x, y, width, height, value, isLeaf } = this.getMeta();
          const text = String(value || ""); // 获取单元格文本内容
          if (!isLeaf) {
            const textStyle = {
              fontSize: 12,
              fill: "#000",
              textAlign: "left",
              textBaseline: "middle", // 垂直基线
            };

            const fontSize = textStyle.fontSize; // 字体大小
            const padding = 8; // 内边距
            const lineHeight = textStyle.fontSize; // 行高
            const availableWidth = width - 2 * padding; // 可用绘制宽度
            // 分行逻辑：根据宽度动态分割文本
            const lines = splitTextIntoLines(text, availableWidth, fontSize);

            // 计算文本总高度并居中
            const totalTextHeight = lines.length * lineHeight;
            const startY = y + (height - totalTextHeight) / 2 + lineHeight / 2; // 起始 Y 坐标;

            // 绘制每行文本
            lines.forEach((line, lineIndex) => {
              let lineY = 0;
              if (lineIndex == 0) {
                lineY = startY + lineIndex * lineHeight; // 当前行的 Y 坐标
              } else {
                lineY = startY + lineIndex * lineHeight + 2; // 当前行的 Y 坐标
              }
              const totalChars = line.length; // 当前行字符数

              // 计算字符间距（分散对齐）
              const spaceBetween =
                totalChars > 1
                  ? (availableWidth - textStyle.fontSize * totalChars) /
                    (totalChars - 1)
                  : 0;

              // 起始 X 坐标
              let startX = x + padding;

              // 绘制每个字符
              [...line].forEach((char, charIndex) => {
                const charX =
                  startX + charIndex * (textStyle.fontSize + spaceBetween); // 当前字符 X 坐标
                const textShape = renderText({
                  group: this,
                  textShape: [this.textShape],
                  style: {
                    ...textStyle,
                    x: charX,
                    y: lineY,
                    text: char,
                  },
                });
                this.addTextShape(textShape);
              });
            });
          } else {
            // console.log("文本：", value, "宽度: ", width);
            // 叶子节点：竖排换行
            const padding = 8; // 内边距
            const textStyle = {
              fontSize: 12,
              fill: "#000",
              textAlign: "left",
              textBaseline: "middle", // 垂直基线
            };

            const lineHeight = textStyle.fontSize; // 行高
            const availableWidth = height - 2 * padding; // 可用高度
            const lines = splitTextIntoLines(
              value || "",
              availableWidth,
              textStyle.fontSize
            ); // 自动换行

            const startX =
              x + (width - lines.length * lineHeight) / 2 + lineHeight / 2; // 垂直居中
            lines.forEach((line, lineIndex) => {
              const totalChars = line.length;
              const spaceBetween =
                totalChars > 1
                  ? (availableWidth - totalChars * textStyle.fontSize) /
                    (totalChars - 1) // 分散对齐计算
                  : 0;
              let startY = y + padding + 12 / 2; // 起始点
              [...line].forEach((char, charIndex) => {
                const charY =
                  startY + charIndex * (textStyle.fontSize + spaceBetween); // 每个字符的 Y坐标
                renderText({
                  group: this,
                  style: {
                    ...textStyle,
                    y: charY,
                    x: startX + lineIndex * lineHeight,
                    text: char,
                    textAlign: "center",
                  },
                });
              });
            });
          }
        }
      }

      class CustomRowCell extends RowCell {
        drawTextShape() {
          const { x, y, width, height, value, isLeaf } = this.meta;
          console.log(this.meta);
          const padding = 10; // 内边距
          const textStyle = {
            fontSize: 12,
            fill: "#000",
            textBaseline: "middle",
          };
          const lineHeight = textStyle.fontSize + 2; // 行高

          if (!isLeaf) {
            const padding = 8; // 内边距
            const textStyle = {
              fontSize: 12,
              fill: "#000",
              textAlign: "left",
              textBaseline: "middle", // 垂直基线
            };

            const lineHeight = textStyle.fontSize * 1.5; // 行高
            const availableWidth = height - 2 * padding; // 可用高度
            const lines = splitTextIntoLines(
              value || "",
              availableWidth,
              textStyle.fontSize
            ); // 自动换行

            const startX =
              x + (width - lines.length * lineHeight) / 2 + lineHeight / 2; // 垂直居中
            lines.forEach((line, lineIndex) => {
              const totalChars = line.length;
              const spaceBetween =
                totalChars > 1
                  ? (availableWidth - totalChars * textStyle.fontSize) /
                    (totalChars - 1) // 分散对齐计算
                  : 0;
              let startY = y + padding + 12 / 2; // 起始点
              [...line].forEach((char, charIndex) => {
                const charY =
                  startY + charIndex * (textStyle.fontSize + spaceBetween); // 每个字符的 Y坐标
                renderText({
                  group: this,
                  style: {
                    ...textStyle,
                    y: charY,
                    x: startX + lineIndex * lineHeight,
                    text: char,
                    textAlign: "center",
                  },
                });
              });
            });
          } else {
            //横向
            console.log("文本：", value, "宽度: ", width);
            // 叶子节点：横排分散对齐并支持换行
            const availableWidth = width - 2 * padding; // 可用宽度
            const lines = splitTextIntoLines(
              value || "",
              availableWidth,
              textStyle.fontSize
            ); // 自动换行

            const startY =
              y + (height - lines.length * lineHeight) / 2 + lineHeight / 2; // 垂直居中
            lines.forEach((line, lineIndex) => {
              const totalChars = line.length;
              const spaceBetween =
                totalChars > 1
                  ? (availableWidth - totalChars * textStyle.fontSize) /
                    (totalChars - 1) // 分散对齐计算
                  : 0;
              let startX = x + padding + 12 / 2; // 起始点
              [...line].forEach((char, charIndex) => {
                const charX =
                  startX + charIndex * (textStyle.fontSize + spaceBetween); // 每个字符的 X 坐标
                renderText({
                  group: this,
                  style: {
                    ...textStyle,
                    x: charX,
                    y: startY + lineIndex * lineHeight,
                    text: char,
                    textAlign: "left",
                  },
                });
              });
            });
          }
        }
      }

      class CustomDataCell extends DataCell {
        getFieldValue() {
          // 获取行 ID 和列 ID
          const { x, y, rowId, colId } = this.getMeta();
          // 分割 `rowId` 和 `colId` 获取具体字段
          const rowFields = rowId.split("[&]").slice(1); // 跳过 'root'
          const colFields = colId.split("[&]").slice(1); // 跳过 'root'

          // 遍历 `displayData` 查找匹配的记录
          const data = this.spreadsheet.dataSet.displayData;
          const valuesField = this.spreadsheet.dataSet.fields.values[0]; // 获取 'value' 字段

          let value = null;
          for (const item of data) {
            // 判断 `rowFields` 和 `colFields` 是否都匹配
            const isRowMatch = rowFields.every(
              (field) => item[field] !== undefined
            );
            const isColMatch = colFields.every(
              (field) => item[field] !== undefined
            );

            if (isRowMatch && isColMatch) {
              value = item[valuesField]; // 获取数据值
              break;
            }
          }

          return value;
        }
      }

      const customTree = [
        {
          field: "a-2",
          title: "其他投入",
          children: [],
          // cellWidth: 100,
          // cellHeight: 120,
          writingMode: "ls",
          fontSize: 14,
        },
        {
          field: "a-1-2",
          title: "基础基础基础基础基础基础基础基础基础",
          // cellWidth: 100,
          // cellHeight: 50,
          fontSize: 14,
          children: [
            {
              field: "a-1-2-1",
              title: "基础拨款子节",
              // cellWidth: 100,
              // cellHeight: 50,
              writingMode: "",
              fontSize: 14,
              children: [
                {
                  field: "a-1-2-1-1",
                  title: "基础拨款子节1基础拨款子节1",
                  // cellWidth: 100,
                  // cellHeight: 150,
                  writingMode: "ls",
                  fontSize: 14,
                },
                {
                  field: "a-1-2-1-2",
                  title: "基础拨款子节2",
                  // cellWidth: 100,
                  // cellHeight: 150,
                  writingMode: "ls",
                  fontSize: 14,
                },
              ],
            },
          ],
        },
        // {
        //   field: "a-1",
        //   title: "财政教育经费投入",
        //   cellWidth: 100,
        //   cellHeight: null,
        //   // children: [
        //   //   {
        //   //     field: "a-1-1",
        //   //     title: "项目经费",
        //   //     cellWidth: 100,
        //   //     cellHeight: 200,
        //   //     // children: [
        //   //     //   {
        //   //     //     field: "bzhjs",
        //   //     //     title: "标\n准\n化\n建\n设",
        //   //     //     cellWidth: 100,
        //   //     //     cellHeight: 50,
        //   //     //     children: [],
        //   //     //     writingMode: "ls",
        //   //     //   },
        //   //     //   {
        //   //     //     field: "xxhjs",
        //   //     //     title: "信\n息\n化\n建\n设",
        //   //     //     cellWidth: 100,
        //   //     //     cellHeight: 50,
        //   //     //     children: [],
        //   //     //     writingMode: "ls",
        //   //     //   },
        //   //     // ],
        //   //   },
        //   // ],
        // },
      ];
      // const customTree = [
      //   {
      //     field: "a-2",
      //     title: "其他投入",
      //     children: [],
      //   },
      //   {
      //     field: "a-1",
      //     title:
      //       "财政教育经费投入收到捡垃圾几点几分解决法鸡打两局基督教啊了解倒垃圾阿斯顿发束带结发阿斯顿发束带结发发阿斯顿发束带结发阿斯顿发束带结发阿斯顿发束带结发阿斯顿发束带结发阿斯顿发束带结发垃圾袋反垃圾飞拉达较大发啦代发发的三到付件拉法基到啦的",
      //     wordTR: "vl",
      //     children: [
      //       {
      //         field: "a-1-1",
      //         title: "项目经费",
      //         children: [
      //           {
      //             field: "bzhjs",
      //             title: "标准化建设标准化建设标准化建设",
      //             children: [],
      //           },
      //           {
      //             field: "xxhjs",
      //             title: "信息化建设",
      //             children: [],
      //           },
      //         ],
      //       },
      //       // {
      //       //   field: "a-1-2",
      //       //   title: "基础拨款",
      //       //   children: [],
      //       // },
      //     ],
      //   },
      // ];

      // 定义省市县的自定义树形结构
      const rowsTreeHierarchy = [
        {
          field: "hz",
          title: "汇总",
          wordTR: "vl",
          description: "汇总",
        },
        {
          field: "beijing",
          title: "北京市",
          wordTR: "vl",
          description: "北京省描述",
          children: [
            {
              field: "fz",
              title: "分计sdfsfdjsaldj",
              wordTR: "vl",
              description: "分计",
              children: [],
            },
            {
              field: "haidian",
              title: "海淀区",
              wordTR: "vl",
              description: "海淀区描述",
              children: [
                {
                  field: "zizhuyuan",
                  title: "紫竹院",
                  description: "紫竹院描述",
                  children: [],
                },
                {
                  field: "zhongguancun",
                  title: "中关村",
                  description: "中关村描述",
                  children: [],
                },
              ],
            },
          ],
        },
        {
          field: "shanghai",
          title: "上海市上海市上海市上",
          description: "上海省描述",
          children: [
            {
              field: "huangpu",
              title: "黄浦区",
              description: "黄浦区描述",
              children: [],
            },
          ],
        },
      ];

      const data = [
        {
          beijing: "北京市",
          haidian: "海淀区",
          zizhuyuan: "紫竹院",
          "a-1": "财政教育经费投入",
          "a-1-1": "项目经费",
          bzhjs: "标准化建设",
          value: 12121,
        },
        {
          beijing: "北京市",
          haidian: "海淀区",
          zizhuyuan: "紫竹院",
          "a-1": "财政教育经费投入",
          "a-1-1": "项目经费",
          xxhjs: "信息化建设",
          value: 322,
        },
        {
          beijing: "北京市",
          haidian: "海淀区",
          zizhuyuan: "紫竹院",
          "a-1": "财政教育经费投入",
          "a-1-2": "基础拨款",
          value: 555,
        },
        {
          shanghai: "上海市",
          huangpu: "黄浦区",
          "a-1": "财政教育经费投入",
          "a-1-2": "基础拨款",
          value: 2127,
        },
      ];

      const s2DataConfig = {
        fields: {
          rows: rowsTreeHierarchy,
          columns: customTree,
          values: ["value"],
        },
        data,
      };

      const s2Options = {
        width: 800,
        height: 1200,
        colCell: (node, spreadsheet, headerConfig) => {
          return new CustomColCell(node, spreadsheet, headerConfig);
        },
        dataCell: (viewMeta, spreadsheet) => {
          return new CustomDataCell(viewMeta, spreadsheet);
        },
        rowCell: (node, spreadsheet, headerConfig) => {
          return new CustomRowCell(node, spreadsheet, headerConfig);
        },
        hierarchyType: "grid",
        style: {
          rowCell: {
            // 固定配置: 行头单元格 100px
            width: 60,
            // 动态配置: 叶子节点 300px, 非叶子节点 200px
            height: (node) => {
              const text = node.value;
              const words = text.split("");
              return words.length * 35;
            },
          },
          colCell: {
            width: 100,
            height: calculateColCellHeight, // 动态设置高度
          },
          // colCfg: {
          //   width: 100,
          // },
        },
      };

      // 初始化 S2 实例
      s2 = new PivotSheet(container.value, s2DataConfig, s2Options);
      s2.render();
    });

    return {
      container,
    };
  },
};
</script>

<style scoped>
.container {
  margin: 20px;
}
</style>
